<template>
    <div class="components_edit_modal">
        <el-dialog title="修改作业" :visible.sync="state" :show-close="true" :close-on-click-modal="false">
            <el-form  :model="queryFormData.homework" :rules="rules"   ref="queryFormData">
                <el-form-item label="作业名称" prop="title">
                    <el-input v-model.trim="queryFormData.homework.title" placeholder="请输入作业名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="作业名称" prop="type">
                    <template>
                        <el-radio v-model="queryFormData.homework.type" label="0">电子</el-radio>
                        <el-radio v-model="queryFormData.homework.type" label="1">纸质</el-radio>
                   </template>
                </el-form-item>

                <el-form-item label="所属课程" prop="courseNo">
                    <el-select v-model.trim="queryFormData.homework.courseNo" placeholder="请选择" @change="changeClassList">
                        <el-option
                            v-for="item in courseList" :key="item.courseNo"
                            :label="item.courseName"
                            :value="item.courseNo">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item  label="成绩比例" prop="proportion">
                    <el-input-number size="mini" width="60" v-model="queryFormData.homework.proportion" :min="0" :max="100"></el-input-number>
                </el-form-item>
                <el-form-item label="作业开始时间" prop="startTime">
                    <el-date-picker
                        v-model.trim="queryFormData.homework.startTime"
                        type="datetime"
                        placeholder="选择日期"
                        clearable>
                      </el-date-picker>
                </el-form-item>
                <el-form-item label="作业结束时间" prop="endTime">
                    <el-date-picker
                        v-model.trim="queryFormData.homework.endTime"
                        type="datetime"
                        placeholder="选择日期"
                        clearable>
                      </el-date-picker>
                </el-form-item>

                <el-form-item label="作业说明" prop="remark" class="el-form-item lineblock textareaBox">
                    <el-input v-model.trim="queryFormData.homework.remark" :rows="2" type="textarea" placeholder="请输入作业说明" clearable></el-input>
                </el-form-item>
                <el-form-item label="作业课件" class="el-form-item lineblock textareaBox">
                    <pl-upload
                        :initionData="attachment"
                        :displaymode="'text'"
                        :imageOnly="false"
                        :multiFile="false"
                        :buttonIds='{select:"selectfiles2",upload:"postfiles2",container:"container2"}'
                        @reloadFiles="reloadFiles" ></pl-upload>
                </el-form-item>
                <div class="scrollBarX">
                    <el-table :data="classeList"  border stripe style="width: 100%">
                        <el-table-column  prop="schoolName"  label="学校" align="center"></el-table-column>
                        <el-table-column  prop="secondSchoolName"  label="学院"  align="center"></el-table-column>
                        <el-table-column  prop="gradeName"  label="年级" align="center"></el-table-column>
                        <el-table-column  prop="professionName"  label="专业" align="center"></el-table-column>
                        <el-table-column  prop="shortName"  label="班级" align="center"></el-table-column>
                        <el-table-column  prop="" label="状态" align="center" width="100">
                            <template slot-scope="scope">
                                <el-checkbox v-model="classeList[scope.$index].check"></el-checkbox>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <el-button style="margin:10px" size="mini" type="primary" icon="el-icon-plus" @click="addAssess">添加</el-button>

                <div class="scrollBarX">
                    <el-table :data="queryFormData.homeworkAssessList"  border stripe style="width: 100%" class="components_edit_tables">
                        <el-table-column label="序号" type="index" align="center" width="50"></el-table-column>
                        <el-table-column  prop="appraisalName"  label="考核点名称"  align="center">
                            <template slot-scope="scope">
                                        <el-input v-model="queryFormData.homeworkAssessList[scope.$index].appraisalName" clearable></el-input>
                                    </template>
                        </el-table-column>
                        <el-table-column  prop="gradeName"  label="考核点占比" align="center">
                            <template slot-scope="scope">
                                        <el-input v-model="queryFormData.homeworkAssessList[scope.$index].score" clearable>
                                        </el-input>
                                    </template>
                        </el-table-column>
                        <el-table-column  prop="remark"  label="描述" align="center">
                            <template slot-scope="scope">
                                        <el-input v-model="queryFormData.homeworkAssessList[scope.$index].remark" clearable>
                                        </el-input>
                                    </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="100">
                            <template slot-scope="scope">

                                <a href="javascript:void(0);" class="link_txt" @click="deleteAssess(scope.$index)">删除</a>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" @click="updateHomework('queryFormData')">确 定</el-button>
                <el-button @click="state = false"  size="small">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {enums} from '@/constant'
    import PlUpload from "../../../common/PlUpload"
    import {config} from "../../../../config.js";
    import moment from 'moment'
    export default {
        components: {
            "pl-upload":PlUpload
        },
        data() {
            // 开始时间点验证
            var checkendTime = (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请选择时间"));
              } else if (this.queryFormData.homework.startTime && this.queryFormData.homework.startTime.getTime() > value.getTime()) {
                return callback(new Error("开始时间必须早于结束时间"));
              }else{
                return callback();
              }
            };
            // 结束时间点验证
            var checkstartTime = (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请选择时间"));
              } else if (this.queryFormData.homework.endTime && this.queryFormData.homework.endTime.getTime() < value.getTime()) {
                return callback(new Error("开始时间必须早于结束时间"));
              }else{
                return callback();
              }
            };
            return {
                state:false,
                queryFormData:{
                    classIds:[],
                    homework:{
                        id:null,
                        title:null,
                        type:'0',
                        courseNo:null,
                        courseName:null,
                        proportion:null,
                        startTime:null,
                        endTime:null,
                        remark:null,
                    },
                    homeworkAssessList:[{
                        appraisalName:null,
                        score:null,
                        remark:null
                    }],
                },
                rules: {
                        title: [
                            { required: true, message: '作业名称不能为空', trigger: 'blur'},
                            { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
                        ],
                        courseNo: [
                            { required: true, message: '请选择课程', trigger: 'change'},
                        ],
                        proportion: [
                            { required: true, message: '请填写正确的成绩占比', trigger: 'blur',type:"number"},
                            // { min: 0, max: 100, message: '只能输入大于0小于100的数（含整数、两位小数）', trigger: 'blur', type:'number',
                            //     transform(value){
                            //         if(!isNaN(value)){
                            //             value = Number(value)
                            //             return value;
                            //         }
                            //         return "";
                            //     }
                            // }
                        ],
                        startTime: [
                            { required: true, message: '请选择开始时间',trigger: 'change',type:"date"},
                            { validator: checkstartTime, trigger: "blur" }
                        ],
                        endTime: [
                            { required: true, message: '请选择结束时间',trigger: 'change',type:"date"},
                            { validator: checkendTime, trigger: "blur" }
                        ],
                        remark: [
                            { min: 2, max: 300, message: '长度在 2 到 300 个字符', trigger: 'blur' }
                        ],
                    },
                courseList:[],
                classeList:[],
                //上传附件
                attachment:[],
            }
        },
        created() {

        },
        mounted() {},
        methods: {
            showDialog(id){
                 if(this.$refs['queryFormData']!==undefined){
                    this.$refs['queryFormData'].resetFields();
                }
                this.state = true;
                this.getHomework(id);
            },
            getHomework(id){
                let self = this;
                self.axios.get(api.homeworkTeacher.detail+id).then((response) => {
                    if (response.data.success) {
                        let data = JSON.parse(JSON.stringify(response.data.data));
                        console.log(JSON.stringify(response.data.data));
                        self.queryFormData={
                            homework:{
                                id:id,
                                title:data.homework.title,
                                type:data.homework.type+"",
                                courseNo:data.homework.courseNo,
                                courseName:data.homework.courseName,
                                proportion:Number(data.homework.proportion),
                                startTime:new Date(data.homework.startTime),
                                endTime:new Date(data.homework.endTime),
                                remark:data.homework.remark,
                            },
                            homeworkAssessList:data.homeworkAssessses
                        };
                        self.courseList = JSON.parse(JSON.stringify(response.data.data.courses));
                        let classeList = JSON.parse(JSON.stringify(response.data.data.classes));
                        for(let i=0;i<classeList.length;i++){
                            classeList[i].check=false;
                            for(let j=0;j<data.homeworkClasses.length;j++){
                                if(classeList[i].id == data.homeworkClasses[j].classId){
                                    classeList[i].check=true;
                                }
                            }
                        }
                        self.classeList = classeList;
                        self.attachment = data.attachment;
                    } else {
                        self.$message.error(response.data.msg);
                    }
                })
            },
            reloadFiles: function (files) {
                let vm = this;
                this.attachment = [];
                files.forEach((item,idnex)=>{
                    let model = {
                        fileRealName: item.fileRealName,
                        objectKey: item.objectKey
                    }
                    this.attachment.push(model)
                })
            },
            changeClassList(courseNo){
                let self = this;
                self.axios.get(api.queryTrainPlanClassByUserId,{
                    params: {
                        courseNo:courseNo
                    }
                }).then((response) => {
                    if (response.data.success) {
                        // console.log(courseNo+"-->"+JSON.stringify(response.data.data));
                        self.classeList = JSON.parse(JSON.stringify(response.data.data));
                    } else {
                        self.$message.error(response.data.msg);
                    }
                })
            },
            //添加作业
            updateHomework(queryFormData){
                let self = this;
                let classeList = this.classeList;
                let queryForm =  this.queryFormData;
                this.$refs['queryFormData'].validate((valid) => {
                    if (valid) {
                        let homeworkAssessList = queryForm.homeworkAssessList;
                        let homeworkAssessListcurrent = [];
                        for(let i=0;i<homeworkAssessList.length;i++){
                            let item={
                                id:homeworkAssessList[i].id,
                                appraisalName:homeworkAssessList[i].appraisalName,
                                score:homeworkAssessList[i].score,
                                remark:homeworkAssessList[i].remark
                            };
                            homeworkAssessListcurrent.push(item);
                        }
                        let queryFormData = {
                            classIds:[],
                            homework:queryForm.homework,
                            homeworkAssessList:homeworkAssessListcurrent,
                            attachment:self.attachment
                        };

                    for(let i=0;i<classeList.length;i++){
                        if(classeList[i].check){
                            queryFormData.classIds.push(classeList[i].id);
                         }
                    }
                    // console.log(queryFormData.homework.courseNo);
                    let queryArr  = this.getCourseNameAndSemesterBycourseNo(queryFormData.homework.courseNo);
                    if(queryArr != null){
                        queryFormData.homework.courseName=queryArr[0];
                        queryFormData.homework.semester=queryArr[1];
                    }


                   // console.log(JSON.stringify(queryFormData));
                    if(queryFormData.classIds.length>0){

                        self.axios.post(api.homeworkTeacher.update,queryFormData).then((response) => {
                            if (response.data.success) {
                                self.$message({
                                    type: 'success',
                                    message: response.data.msg,
                                });
                                self.$parent.$refs.homeworkTable.$emit('vuetable:refresh');
                                self.state = false;
                            } else {
                                self.$message.error(response.data.msg);
                            }

                        });
                        }else{
                            self.$message.error('请选择班级！');
                        }
                    } else {
                        return false;
                    }
                });
            },
            getCourseNameAndSemesterBycourseNo(courseNo){
                let courseList = this.courseList;
                for(let i=0;i<courseList.length;i++){
                    if(courseList[i].courseNo == courseNo){
                        return (courseList[i].courseName+","+courseList[i].semester).split(",");
                    }
                }
                return null;
            },
            addAssess(){
                this.queryFormData.homeworkAssessList.push({
                        appraisalName:null,
                        score:null,
                        remark:null
                })
            },
            deleteAssess(index){
                let homeworkAssessListCurrent = [];
                let homeworkAssessList = this.queryFormData.homeworkAssessList;
                for(let i=0;i<homeworkAssessList.length;i++){
                    if(i != index){
                        homeworkAssessListCurrent.push(homeworkAssessList[i]);
                    }
                }
                this.queryFormData.homeworkAssessList = homeworkAssessListCurrent;
            }
        },


    };
</script>
<style scoped>
.components_edit_modal .el-form-item__label{
    width: 90px;
}
.selectContainer{
    background-color: #fff;
    margin-left: 25px;
    width:210px;
    height:181px;
    border: 1px solid #00BBBD;
}
.selectContainer .item{
    width:30px;
    height:30px;
    text-align: center;
}
.opration_button{
    margin:10px;
}
.el-date-editor.el-input, .el-date-editor.el-input__inner{
    width: 100%;
}
.components_edit_modal .el-textarea .el-form-item__error{
    margin-top: 0px;
}
</style>